package com.zp.base.impl.printPdfTemplate;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.entity.printPdfTemplate.PrintPdfTemplate;
import com.zp.base.entity.printPdfTemplate.bo.PrintPdfTemplateBo;
import com.zp.base.entity.printPdfTemplate.vo.PrintPdfTemplateVo;
import com.zp.base.mapper.printPdfTemplate.PrintPdfTemplateMapper;
import com.zp.base.service.printPdfTemplate.IPrintPdfTemplateService;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.oss.config.FileConfig;
import com.zp.common.oss.config.uploadMessage;
import com.zp.common.oss.exception.file.FileNameLengthLimitExceededException;
import com.zp.common.oss.exception.file.FileSizeLimitExceededException;
import com.zp.common.oss.exception.file.InvalidExtensionException;
import com.zp.common.oss.file.FileUploadUtils;
import com.zp.common.oss.file.MimeTypeUtils;
import com.zp.common.pdf.HisReportPdf;
import com.zp.common.pdf.test;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * pdf打印模板字典Service业务层处理
 *
 * @author zhang peng
 * @ date 2023-09-18
 */
@RequiredArgsConstructor
@Service
public class PrintPdfTemplateServiceImpl implements IPrintPdfTemplateService {

    private final PrintPdfTemplateMapper baseMapper;

    /**
     * 查询pdf打印模板字典
     */
    @Override
    public PrintPdfTemplateVo queryById (String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询pdf打印模板字典列表(分页)
     */
    @Override
    public TableDataInfo<PrintPdfTemplateVo> queryPageList (PrintPdfTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PrintPdfTemplate> lqw = buildQueryWrapper(bo);
        Page<PrintPdfTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询pdf打印模板字典列表(不分页)
     */
    @Override
    public List<PrintPdfTemplateVo> queryList (PrintPdfTemplateBo bo) {
        LambdaQueryWrapper<PrintPdfTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PrintPdfTemplate> buildQueryWrapper (PrintPdfTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PrintPdfTemplate> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTemplateType()), PrintPdfTemplate::getTemplateType, bo.getTemplateType());
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), PrintPdfTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(StringUtils.isNotBlank(bo.getFilePath()), PrintPdfTemplate::getFilePath, bo.getFilePath());
        lqw.eq(StringUtils.isNotBlank(bo.getTemplateCode()), PrintPdfTemplate::getTemplateCode, bo.getTemplateCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), PrintPdfTemplate::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getFileUrl()), PrintPdfTemplate::getFileUrl, bo.getFileUrl());
        return lqw;
    }

    /**
     * 新增pdf打印模板字典
     */
    @Override
    public Boolean insertByBo (PrintPdfTemplateBo bo) {
        PrintPdfTemplate add = BeanUtil.toBean(bo, PrintPdfTemplate.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改pdf打印模板字典
     */
    @Override
    public Boolean updateByBo (PrintPdfTemplateBo bo) {
        PrintPdfTemplate update = BeanUtil.toBean(bo, PrintPdfTemplate.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (PrintPdfTemplate entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除pdf打印模板字典
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * @return
     * @Author zhangpeng
     * @Description //上传文件到服务器
     * @ date 15:56 2023/10/16
     **/
    public static final uploadMessage uploadTemplate (String baseDir, MultipartFile file, String templateName,
                                                      String templateCode, String templateType, String orgId, String filePath, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
        int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        // 文件大小校验
        FileUploadUtils.assertAllowed(file, allowedExtension);
        String fileName = file.getOriginalFilename();
        String extension = FileUploadUtils.getExtension(file);
        if (StringUtils.isEmpty(filePath)) {
            // 组装路径 ： 机构id  + 系统路径标识符 + 系统路径标识符 + 模板类型 + 系统路径标识符 + 模板名称代码  + 系统路径标识符 + 模板文件名  + File.separator + templateCode
            fileName = orgId + File.separator + templateType + File.separator + file.getOriginalFilename();
        } else {
            File judgeFile = new File(fileName);
        }
        File desc = FileUploadUtils.getAbsoluteFileReport(baseDir, fileName);
        file.transferTo(desc);
        String pathFile = desc.getPath();
        String urlFile = FileUploadUtils.getPathFileName(baseDir, fileName);
        uploadMessage uploadMessage = new uploadMessage();
        uploadMessage.setFilePath(pathFile);
        uploadMessage.setFileUrl(urlFile);
        return uploadMessage;
    }

    /**
     * @return
     * @Author zhangpeng
     * @Description //TODO 上传pdf到服务器
     * @ date 14:26 2023/9/21
     **/
    @Override
    public uploadMessage uploadPdfFile (String baseDir, MultipartFile file, String templateName, String templateCode,
                                        String templateType, String orgId, String filePath) {
        uploadMessage uploadMessage = new uploadMessage();
        try {
            return uploadTemplate(baseDir, file, templateName, templateCode, templateType, orgId, filePath, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * ireport模板下载
     *
     * @param id
     * @param response
     * @param request
     */
    @Override
    public void downloadFile (String id, HttpServletResponse response, HttpServletRequest request) {
        PrintPdfTemplateVo printPdfTemplateVo = baseMapper.selectVoById(id);
        if (ObjectUtils.isNotEmpty(printPdfTemplateVo)) {
            String staticPath = FileConfig.getStaticPath();
            String templateUrl = staticPath + printPdfTemplateVo.getFileUrl();
            FileUploadUtils.downLoadFile(templateUrl, request, response);
        }
    }

    /**
     * ireport 报表预览打印
     *
     * @param id
     * @param request
     * @param response
     */
    @Override
    public void printTest (String id, HttpServletRequest request, HttpServletResponse response) {
        PrintPdfTemplateVo printPdfTemplateVo = baseMapper.selectVoById(id);
        if (ObjectUtils.isNotEmpty(printPdfTemplateVo)) {
            String staticPath = FileConfig.getStaticPath();
            String templateUrl = staticPath + printPdfTemplateVo.getFileUrl();
            HisReportPdf reportPdf = new HisReportPdf(templateUrl, "");
            // 参数
            Map<String, Object> map = new HashMap<>();
            List<test> list = new ArrayList<>();
            map.put("aaaa", "CsssT");
            map.put("vvvv", "CssswT");

            test aaa = new test();
            aaa.setAaa("22222a");
            aaa.setBbb("11111b");
            test aaa1 = new test();
            aaa1.setAaa("22222a");
            aaa1.setBbb("22222b");
            list.add(aaa1);
            list.add(aaa);
            map.put("lists", list);
            reportPdf.setParam(map);
            try {
                reportPdf.renderMergedOutputModel(map, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
